<template>
    <el-form label-width="100px">
        <el-form-item label="SPU 名称">{{ spuInfo.spuName }}</el-form-item>
        <el-form-item label="SKU 名称">
            <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
        </el-form-item>
        <el-form-item label="价格(元)">
            <el-input type="number" v-model="skuInfo.price"></el-input>
        </el-form-item>
        <el-form-item label="重量(千克)">
            <el-input type="number" v-model="skuInfo.weight"></el-input>
        </el-form-item>
        <el-form-item label="规格描述">
            <el-input type="textarea" v-model="skuInfo.skuDesc" placeholder="规格描述" rows="4"></el-input>
        </el-form-item>

        <el-form-item label="平台属性">
            <el-form label-width="100px" :inline="true">
                <!-- 遍历生成平台属性下拉框 -->
                <el-form-item v-for="attr in attrList" :key="attr.id" :label="attr.attrName">
                    <el-select v-model="attr.attrIdValueId" placeholder="请选择">
                        <el-option v-for="item in attr.attrValueList" :key="item.id"
                            :value="`${item.attrId}:${item.id}`" :label="item.valueName"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>

        <el-form-item label="销售属性">
            <el-form label-width="100px" :inline="true">
                <!-- 遍历生成销售属性下拉框 -->
                <el-form-item v-for="attr in spuSaleAttrList" :key="attr.id" :label="attr.saleAttrName">
                    <el-select v-model="attr.SaleIdValueId" placeholder="请选择">
                        <el-option v-for="item in attr.spuSaleAttrValueList" :key="item.id"
                            :value="`${item.baseSaleAttrId}:${item.id}`" :label="item.saleAttrValueName"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>

        <el-form-item label="图片列表">
            <el-table :data="spuImageList" border stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="图片">
                    <template v-slot="{row}">
                        <img :src="row.imgUrl" width="120" height="120" />
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="imgName"></el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{row}">
                        <el-tag v-if="row.isDefault === '1'" type="success" size="small">默认图片</el-tag>
                        <el-button v-else type="primary" size="small" @click="changeDefault(row)">设为默认</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="default" @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import type { SkuListItemType } from "@/api/sku";
import { ElMessage } from "element-plus";

export default defineComponent({
    name: "SkuFrom",
});
</script>

<script setup lang="ts">
import useAttrStore from "@/stores/attr"
import { storeToRefs } from "pinia"
import { onMounted, ref } from "vue"
import { requestSpuImageList, requestSpuSaleAttrList, type SpuImageItemType, type SpuImageListType, type SpuSaleAttrListType, type supInfoType } from "@/api/spu";
import { requestGetAttrList, type reqAttrListType } from "@/api/attr"
import { requestSaveSkuInfo } from "@/api/sku"


//1.接收父组件的自定义事件点击取消调用，显示不同的子组件
const emit = defineEmits<{
    (event: 'setState', state: number, row?: supInfoType): void
}>()

//2.接收spuInfo等下发送修改或添加请求要用
const props = defineProps<{
    spuInfo: supInfoType
}>()

//3.接收pinia数据
const attrStore = useAttrStore()
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore)

//定义添加sku要发送的数据
const skuInfo = ref<SkuListItemType>({
    skuName: "",
    price: 0,
    skuDesc: "",
    weight: "",

    spuId: props.spuInfo.id,
    category3Id: props.spuInfo.category3Id as number,
    tmId: props.spuInfo.tmId as number,

    skuDefaultImg: "",

    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
})


//定义数据保存初始化请求回来的数据啊
const attrList = ref<reqAttrListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
//请求初始化需要的数据的函数
const getInitData = async () => {
    const promise1 = requestGetAttrList(
        category1Id.value as number,
        category2Id.value as number,
        category3Id.value as number
    )
    const promise2 = requestSpuSaleAttrList(props.spuInfo.id as number)
    const promise3 = requestSpuImageList(props.spuInfo.id as number)

    //同时发送3个请求
    const result = await Promise.all([promise1, promise2, promise3])

    //把请求回来的数据保存到我们定义的数据中
    attrList.value = result[0]
    spuSaleAttrList.value = result[1]
    spuImageList.value = result[2]
}
//4.初始化请求需要的数据
onMounted(() => {
    getInitData()
})


//5.点击切换默认图片的回调
const changeDefault = (row: SpuImageItemType) => {
    //排他
    spuImageList.value.forEach((item) => {
        item.isDefault = "0"
    })
    //显示当前的为tag
    row.isDefault = "1"
}


//选择的图片数据的类型
interface chooseImage {
    id: number,
    imgName: string,
    imgUrl: string,
    isDefault: string,
    spuId: number,
}
//选中的图片组成的数组
//定义数据保存选择的图片
const newSpuInageList = ref<chooseImage[]>([])
//6.选中图片的回调
const handleSelectionChange = (val: chooseImage[]) => {
    newSpuInageList.value = val
}

//7.点击保存的回调
const save = async () => {
    //处理平台属性数据
    attrList.value.forEach((item) => {
        //把选中的平台属性插入到skuInfo中
        if (item.attrIdValueId) {
            const newSkuAttr = {
                attrId: +item.attrIdValueId.split(":")[0],
                valueId: +item.attrIdValueId.split(":")[1]
            }
            skuInfo.value.skuAttrValueList?.push(newSkuAttr)
        }
    })

    //处理销售属性数据
    spuSaleAttrList.value.forEach((item) => {
        //把选中的销售属性插入到skuInfo
        if (item.SaleIdValueId) {
            const newSaleAttr = {
                saleAttrId: +item.SaleIdValueId.split(":")[0],
                saleAttrValueId: +item.SaleIdValueId.split(":")[1]
            }
            skuInfo.value.skuSaleAttrValueList?.push(newSaleAttr)
        }
    })

    //处理图片列表数据
    newSpuInageList.value.forEach((item) => {
        //收集默认图片
        if (item.isDefault === '1') {
            skuInfo.value.skuDefaultImg = item.imgUrl
        }

        //收集选中的图片
        const newImg = {
            imgName: item.imgName,
            imgUrl: item.imgUrl,
            spuImgId: item.id,
            isDefault: item.isDefault
        }

        //插入到skuInfo的图片列表中
        skuInfo.value.skuImageList?.push(newImg)
    })

    //开始发送添加请求
    try {
        await requestSaveSkuInfo(skuInfo.value)
        //成功提示
        ElMessage.success("添加sku成功!")
        //回到spuList
        emit('setState' , 0)
    } catch (e) {
        ElMessage.error("添加sku失败!")
    }

}

</script>